package com.sczmgk.track.activity.trackactivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.sczmgk.track.MyApp;
import com.sczmgk.track.R;
import com.sczmgk.track.activity.ChangePwdActivity;
import com.sczmgk.track.activity.SignRecordActivity;
import com.sczmgk.track.activity.TrackRecordActivity;
import com.sczmgk.track.base.BaseMapActivity;
import com.sczmgk.track.constant.Constant;
import com.sczmgk.track.db.impl.UserDaoImpl;
import com.sczmgk.track.dialog.DialogFactory;
import com.sczmgk.track.dialog.MessageDialog;
import com.sczmgk.track.entity.User;
import com.sczmgk.track.entity.bean.UserData;
import com.sczmgk.track.httpUtils.MyHttp;
import com.sczmgk.track.popup.PupDialog;
import com.sczmgk.track.test.MyCallback;
import com.sczmgk.track.utils.BitmapUtil;
import com.sczmgk.track.utils.BitmapUtils;
import com.sczmgk.track.utils.CacheUtils;
import com.sczmgk.track.utils.CommonUtils;
import com.sczmgk.track.utils.FileUtil;
import com.sczmgk.track.utils.MyLog;
import com.sczmgk.track.utils.MyToast;
import com.sczmgk.track.utils.PictureUtil;
import com.sczmgk.track.utils.Tools;
import com.sczmgk.track.utils.UIUtils;
import com.sczmgk.track.utils.UserImageUtils;
import com.sczmgk.track.view.HeadPortraitView;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.sczmgk.track.constant.Constant.managerPhone;

/**
 * 轨迹追踪
 */
public class TracingActivity extends BaseMapActivity {

    private static final int REQUEST_CODE = 321;
    private static final int REFRESH_USER = 111;
    private static final int SET_DEFAULT_HEAD = 112;
    private static final int CHANGE_DEVICE_MSG = 113;
    private HeadPortraitView mPhoto;
    private TextView mTvName;
    private TextView mTvJobNum;
    private User user;
    private LinearLayout mLayoutRecord;
    private LinearLayout mLayoutSignRecord;
    private LinearLayout mLayoutChangePhoto;
    private LinearLayout mLayoutChangePwd;
    private LinearLayout mLayoutActive;
    private MessageDialog activeDialog;
    private MessageDialog changePhoneDialog;


    @Override
    public void handleMessage(Message msg) {
        switch (msg.what){
            case REFRESH_USER:
                refreshUi();
                break;
            case SET_DEFAULT_HEAD:
                //设置默认头像
                mPhoto.getImageView().setImageResource(R.drawable.personal_default);
                break;
            case CHANGE_DEVICE_MSG:
                //设备更换
                if (activeDialog == null) {
                    callPhoneDialog();
                } else if (!activeDialog.isShowing()) {
                    callPhoneDialog();
                }
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        CommonUtils.addActivity(this);
        setLeftBtnBackground(R.drawable.left_personal_center);
        setTitle(R.string.tracing_title);
        setShareBtnVisiable(View.VISIBLE);
        setShareBtnBGResource(R.drawable.icon_settings);
        setShareBtnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                UIUtils.startActivityForResult(TracingActivity.this, TracingOptionsActivity.class, Constant.REQUEST_CODE);
            }
        });
        initLeftMenuView();
        setListener();
        CacheUtils.setREcordStatus(this,false);
        CacheUtils.setEnableStatus(this,false);

        user = UserDaoImpl.getLoginUser(TracingActivity.this);
        if (user.imeistatus == User.SIGN_ENABLE) {
            checkRecordStatus();
        }
    }


    /**
     * 初始化左侧界面的控件
     */
    private void initLeftMenuView() {

        //头像
        mPhoto = (HeadPortraitView) findViewById(R.id.hpv_left_menu_photo);

        //姓名
        mTvName = (TextView) findViewById(R.id.tv_left_menu_name);

        //工号
        mTvJobNum = (TextView) findViewById(R.id.tv_left_menu_job_num);

        //行程记录
        mLayoutRecord = (LinearLayout) findViewById(R.id.ll_left_function_record);

        //签到记录
        mLayoutSignRecord = (LinearLayout) findViewById(R.id.ll_left_function_sign_record);

        //更换头像
        mLayoutChangePhoto = (LinearLayout) findViewById(R.id.ll_left_function_change_head_photo);

        //更改密码
        mLayoutChangePwd = (LinearLayout) findViewById(R.id.ll_left_function_change_pwd);

        //设备激活
        mLayoutActive = (LinearLayout) findViewById(R.id.ll_left_function_device_activation);

        initLeftMenuData();
    }

    /**
     * 左侧菜单功能点击事件
     */
    private class MyLeftClickListener implements View.OnClickListener{
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.ll_left_function_record:
                    //行程记录
                    MyToast.show(TracingActivity.this, "行程记录");
                    UIUtils.startActivity(TracingActivity.this, TrackRecordActivity.class);
                    break;
                case R.id.ll_left_function_sign_record:
                    //签到记录
                    MyToast.show(TracingActivity.this, "签到记录");
                     UIUtils.startActivity(TracingActivity.this,SignRecordActivity.class);
                    break;
                case R.id.ll_left_function_change_head_photo:
                    //更换头像
                    checkCamera(0);
                    break;
                case R.id.ll_left_function_change_pwd:
                    //修改密码
                    UIUtils.startActivity(TracingActivity.this,ChangePwdActivity.class);
                    break;
                case R.id.ll_left_function_device_activation:
                    //设备激活
                    switch (user.imeistatus){
                        case Constant.DEVICE_CHANGE_PHONE :
                            //更换手机
                            if (changePhoneDialog == null) {
                                showPhoneChangeDialog();
                            } else if (!changePhoneDialog.isShowing()) {
                                showPhoneChangeDialog();
                            }
                            break;
                        case Constant.DEVICE_NOT_ACTIVE :
                            //未激活
                            if (activeDialog == null) {
                                showActiveDialog();
                            } else if (!activeDialog.isShowing()) {
                                showActiveDialog();
                            }
                            break;
                    }
                    break;
            }
        }
    }

    /**
     * 展示更换设备的dialog
     */
    private void showPhoneChangeDialog() {
        changePhoneDialog = DialogFactory.chooseDialog(TracingActivity.this, getResources().getString(R.string.device_change_des), getResources().getString(R.string.sure), new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                loadPhoneChange();

            }
        });
    }

    /**
     * 更换设备申请
     */
    private void loadPhoneChange() {
        Map<String,Object> maps = new HashMap<>();
        maps.put("userid",CacheUtils.getLoginUserid(TracingActivity.this));
        maps.put("imei",MyApp.imei);
        MyHttp.requestDataT(TracingActivity.this, Constant.CHANGE_DEVICE_URL, MyHttp.POST, null, maps, null, false, null, new MyCallback() {
            @Override
            public void onSuccess(Object o) {

            }

            @Override
            public void onUnknownError() {

            }

            @Override
            public void onError(String msg) {

            }

            @Override
            public void onSuccess() {
                mHandler.sendEmptyMessage(CHANGE_DEVICE_MSG);
            }
        });
    }

    /**
     * 展示拨打电话的dialog
     */
    private void callPhoneDialog() {
        DialogFactory.chooseDialog(TracingActivity.this, getResources().getString(R.string.device_call_phone_des), getResources().getString(R.string.call), new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                checkPhone(managerPhone);
            }
        });
    }

    /**
     * 展示设备激活的dialog
     */
    private void showActiveDialog() {
        activeDialog = DialogFactory.chooseDialog(TracingActivity.this, getResources().getString(R.string.device_active_des), getResources().getString(R.string.sure), new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                deviceActive();
            }
        });
    }

    /**
     * 激活设备
     */
    private void deviceActive() {
        showLoadingDiaLog();
        Map<String, Object> dataMaps = new HashMap<>();
        dataMaps.put("userid", CacheUtils.getLoginUserid(TracingActivity.this));
        dataMaps.put("imei", MyApp.imei);
        MyHttp.requestDataT(TracingActivity.this, Constant.DEVICE_ACTIVE_URL, MyHttp.POST, null, dataMaps, null, false, null, new MyCallback() {
            @Override
            public void onSuccess(Object o) {
                dismissLoadingDiaLog();
            }

            @Override
            public void onUnknownError() {
                dismissLoadingDiaLog();
            }

            @Override
            public void onError(String msg) {
                showErrorMsg(msg);
                dismissLoadingDiaLog();
            }

            @Override
            public void onSuccess() {
                dismissLoadingDiaLog();

                User user = UserDaoImpl.getLoginUser(TracingActivity.this);
                user.imeistatus = 0;
                UserDaoImpl.getIntance(TracingActivity.this).updata(user);
                Tools.showChangeToast(TracingActivity.this,R.drawable.active_success);
                mHandler.sendEmptyMessage(REFRESH_USER);
            }
        });
    }

    /**
     * 初始化左侧菜单功能模块数据
     */
    private void initLeftMenuData() {


    }

    @Override
    protected void onResume() {
        super.onResume();

        boolean isLogin = CacheUtils.getLoginStatus(TracingActivity.this);
        //TODO 测试
        if (!isLogin) {
            //未登录时刷新ui
            refreshLoginOutUI();
            return;
        }
        refreshUi();
    }

    private void refreshLoginOutUI() {
        mHandler.sendEmptyMessage(SET_DEFAULT_HEAD);
        mTvJobNum.setText("");
    }

    private void refreshUi() {
        //获取用户信息
        user = UserDaoImpl.getLoginUser(TracingActivity.this);
        if (user == null) {
            CacheUtils.cacheLoginStatus(TracingActivity.this, false);
            return;
        }

        mLayoutActive.setVisibility(user.imeistatus == 0 ? View.GONE : View.VISIBLE);

        //设置工号
        mTvJobNum.setText(user.worknumber);

        //设置名字
        mTvName.setText(user.username);

        //设置头像,为空则去下载头像
        if (!Tools.isEmpty(user.imageLocalPath)) {
            Bitmap bitmap = BitmapUtils.getBitmap(user.imageLocalPath, 200, 200);
            if (bitmap != null) {
                MyLog.d(TAG, "已取到用户图片");
                mPhoto.getImageView().setImageBitmap(bitmap);
            } else {
                downPic();
            }
        } else {
            downPic();
        }
    }


    @Override
    protected boolean getIsShowLeft() {
        return true;
    }

    @Override
    public int getMapType() {
        return TRACING_ACITIVITY_TYPE;
    }

    private void setListener() {

        btnSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(TracingActivity.this, SignActivity.class);
                startActivityForResult(intent, REQUEST_CODE);
            }
        });

        //行程记录
        mLayoutRecord.setOnClickListener(new MyLeftClickListener());
        //签到记录
        mLayoutSignRecord.setOnClickListener(new MyLeftClickListener());
        //更换头像
        mLayoutChangePhoto.setOnClickListener(new MyLeftClickListener());
        //更改密码
        mLayoutChangePwd.setOnClickListener(new MyLeftClickListener());
        //设备激活
        mLayoutActive.setOnClickListener(new MyLeftClickListener());

    }

    @Override
    public boolean getIsNeedLogin() {
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (trackApp != null && trackApp.trackConf != null) {
            CommonUtils.saveCurrentLocation(trackApp);
            if (trackApp.trackConf.contains("is_trace_started")
                    && trackApp.trackConf.getBoolean("is_trace_started", true)) {
                // 退出app停止轨迹服务时，不再接收回调，将OnTraceListener置空
                trackApp.mClient.setOnTraceListener(null);
                trackApp.mClient.stopTrace(trackApp.mTrace, null);
            } else {
                trackApp.mClient.clear();
            }
            trackApp.isTraceStarted = false;
            trackApp.isGatherStarted = false;
            SharedPreferences.Editor editor = trackApp.trackConf.edit();
            editor.remove("is_trace_started");
            editor.remove("is_gather_started");
            editor.apply();
            BitmapUtil.clear();
        }
    }


    /**
     * 下载图片，并更新界面
     */
    private void downPic() {
        UserImageUtils.downLoadPic(TracingActivity.this, new PictureUtil.OnsavePicListener() {
            @Override
            public void onSuccess() {
                mHandler.sendEmptyMessage(REFRESH_USER);
            }

            @Override
            public void onFailure(String msg) {
                mHandler.sendEmptyMessage(SET_DEFAULT_HEAD);
            }
        });
    }

    @Override
    public void onSelectCamera(int position) {
        super.onSelectCamera(position);
        showPup(PupDialog.ID_PHOTO, new PhotoPupEvent());
    }

    @Override
    public int getLayoutResId() {
        return R.layout.activity_tracing;
    }

    @Override
    public void onSelectedPhonePermission(String phoneNumber) {
        super.onSelectedPhonePermission(phoneNumber);
        CommonUtils.callPhone(TracingActivity.this ,phoneNumber);
    }

    /**
     * 选择图片pop的点击事件
     */
    class PhotoPupEvent implements PupDialog.PupEvent {
        @Override
        public void itemOnClick(PupDialog pupid, View item, int position) {
            switch (position) {
                case 0:
                    takePhoto();
                    break;
                case 1:
                    // 点击了选择图片的处理
                    startActivityForResult(new Intent(Intent.ACTION_PICK, null).setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*"), Param.TAKE_PICTURE_SIGN);
                    break;
                default:
                    break;
            }
            pupid.dismiss();
        }
    }

    /***
     * 拍照
     */
    private void takePhoto() {
        // 点击了照相的处理
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File file = new File(FileUtil.RESOURCE_USER_IMAGE_CACHE_PATH);
        if (!file.exists()) {
            file.mkdirs();
        }
        String mPhotoPath = FileUtil.RESOURCE_USER_IMAGE_CACHE_PATH + File.separator + "captureTemp.png";
        MyLog.i(TAG, "点击了照相     mPhotoPath:  " + mPhotoPath);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mPhotoPath)));//图片输出的URL
        intent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, Configuration.ORIENTATION_PORTRAIT);
        startActivityForResult(intent, Param.PHOTOTAKEN_REQUEST_SIGN);
    }

    public static class Param {
        /**
         * intent 传递联系人是否上传图像的key
         */
        public static final String INTENT_KEY_ISLoadLOGINUSERPHOTO = "loadloginuserphonto";
        public static final String INTENT_KEY_UPDAEINFO = "updateinfo";
        public static final int RESULT_CODE_UPDATE_NICKNAME = 0;
        public static final int RESULT_CODE_UPDATE_AREA = 2;
        public static final int PHOTOTAKEN_REQUEST_SIGN = 1010;

        /**
         * 系统相册返回
         */
        public static final int TAKE_PICTURE_SIGN = 1030;
        /**
         * 自定义相册返回
         */
        public static final int REQUEST_CODE_SELECT_PHOTO = 1040;
        /**
         * 图像裁切后的回调
         */
        public static final int REQUEST_PHOTO_RESULT = 204;

        /**
         * 更改兴趣标签的请求码
         */
        private static final int REQUEST_CHANGE_MY_CARE = 101;

        /**
         * 更改昵称的请求码
         */
        private static final int REQUEST_CHANGE_USER_INFO = 103;

        /**
         * 更改性别的请求码
         */
        private static final int REQUEST_CHANGE_SEX = 104;

        /**
         * 更改手机号的请求码
         */
        private static final int REQUEST_CHANGE_PHONE = 105;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case Param.PHOTOTAKEN_REQUEST_SIGN: // 拍照
                    // 拍照返回
                    String mPhotoPath = FileUtil.RESOURCE_USER_IMAGE_CACHE_PATH + File.separator + "captureTemp.png";
                    MyLog.i(TAG, "拍照返回了..... mPhotoPath:  " + mPhotoPath);
                    File file = new File(mPhotoPath);
                    FileInputStream fis = null;
                    try {
                        fis = new FileInputStream(file);
                        if (fis == null) {
                            return;
                        }
                    } catch (FileNotFoundException e1) {
                        e1.printStackTrace();
                        return;
                    }
                    if (file.isFile()) {
                        PictureUtil.startPhotoZoomClipLimit(Uri.fromFile(file), mHandler, this, Param.REQUEST_PHOTO_RESULT, 1, 1, true);
                    }
                    break;

                case Param.REQUEST_CHANGE_MY_CARE:
                case Param.REQUEST_CHANGE_USER_INFO:
                case Param.REQUEST_CHANGE_SEX:
                case Param.REQUEST_CHANGE_PHONE:
                    user = UserDaoImpl.getIntance(TracingActivity.this).findByQuery(MyApp.loginUserUid);
                    if (user != null) {
                        mHandler.sendEmptyMessage(REFRESH_USER);
                    }
                    break;
                case Param.TAKE_PICTURE_SIGN: // 选择相册
                    // 选择相册返回
                    MyLog.i(TAG, "选择相册返回了.....");
                    if (intent == null) {
                        return;
                    }
                    PictureUtil.startPhotoZoomClipLimit(intent.getData(), mHandler, this, Param.REQUEST_PHOTO_RESULT, 1, 1, false);
                    break;
                case Param.REQUEST_PHOTO_RESULT://
                    MyLog.d(TAG, "裁剪图片返回了---------------------");
                    // 防止数据为空
                    if (intent == null)
                        return;
                    if (PictureUtil.getClipTempFile() != null) {
                        compressPic(PictureUtil.getClipTempFile());
                    }
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 压缩图片
     */
    private void compressPic(final String imagePath) {

        final String uploadPicTempFilePath = FileUtil.getUploadPicTempFilePath();
        MyLog.d(TAG, "原图片路径 :　 " + imagePath + "临时文件路径　：　" + uploadPicTempFilePath);

        //1.将图片压缩存入临时文件
        BitmapUtils.compressBitmap(uploadPicTempFilePath, imagePath, 400, 400, new BitmapUtils.CompressBitmapCallback() {

            @Override
            public void compress(final String tempPath) {
                MyLog.d(TAG, "另存压缩临时图片的路径是：" + tempPath);
                //更新用户信息
                uploadPhoto(imagePath, tempPath);
            }
        });
    }

    private void uploadPhoto(final String imagePath, final String tempPath) {

        final Map<String, Object> dataMaps = new HashMap<>();
        dataMaps.put("userid", CacheUtils.getLoginUserid(TracingActivity.this));
        dataMaps.put("imei", MyApp.imei);

        //图片描述数据
        final Map<String, Object> fileTypeMaps = new HashMap<>();
        int module = 7002;
        String remark = "remark";
        fileTypeMaps.put("module", module);
        fileTypeMaps.put("remark", remark);
        final List<String> filePaths = new ArrayList<>();
        filePaths.add(imagePath);
        MyHttp.requestDataT(TracingActivity.this, Constant.UPDATE_HEAD_PHOTO, MyHttp.UPLOAD_FILE, filePaths, dataMaps, fileTypeMaps, false, null, new MyCallback<UserData>() {
            @Override
            public void onSuccess(UserData o) {
                boolean deleteDirectory = FileUtil.delete(tempPath);
                if (deleteDirectory) {
                    MyLog.d(TAG, "删除临时图片成功 -------------" + tempPath);
                } else {
                    MyLog.e(TAG, "删除临时图片失败----------路径是：" + tempPath);
                }

                String path = FileUtil.getUserCaptureCacheFilePath(MyApp.loginUserUid + "");
                //提交成功后将地址更新至数据库
                FileUtil.copyFile(new File(PictureUtil.getClipTempFile()), new File(path));
                user.imageLocalPath = path;
                try {
                    parseJson(o.data);
                } catch (Exception e) {
                    MyLog.e(TAG, "解析json错误");
                    e.printStackTrace();
                }
            }

            @Override
            public void onUnknownError() {

                dismissLoadingDiaLog();
            }

            @Override
            public void onError(String msg) {
                showErrorMsg(msg);
            }

            @Override
            public void onSuccess() {

            }
        });
    }

    private void parseJson(User newUser) {
        UserDaoImpl.updateUser(TracingActivity.this, newUser, user);
        mHandler.sendEmptyMessage(REFRESH_USER);
    }

    @Override
    public boolean isLockLeft() {
        return true;
    }
}
